package com.iter.devbox.stream;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;

import com.google.common.collect.Lists;

public class StreamAPI {

	public static void main(String[] args) {
		//Guava的Lists工具类
		List<Integer> lists = Lists.newArrayList(1, null, 3, 4, null, 6);
		//创建Stream-->转换Stream-->聚合
		long count = lists.stream().filter(x -> x != null).count();
		System.out.println(count);
		
		//创建Strem的一种方式
		Stream<Integer> integerStream = Stream.of(1, 2, 3, 5);
		Stream<String> stringStream = Stream.of("taobao");
		System.out.println(integerStream.count());
		System.out.println(stringStream.count());
		
		//创建Strem的一种方式，生成一个无限长度的Stream
		Stream<Double> stream = Stream.generate(new Supplier<Double>() {//supplier供应商、供应者
		    @Override
		    public Double get() {
		        return Math.random();
		    }
		}).limit(2000);//限制生成2000次，否则无限生成
		System.out.println(stream.count());
		Stream.generate(() -> Math.random()).limit(15);
		Stream.generate(Math::random).limit(10);
		
		Stream.iterate(1, item -> item + 1).limit(10).forEach(System.out::println);
		
		//创建Strem的一种方式
		List<String> mylists = new LinkedList<String>();
		mylists.add("1");
		mylists.add("2");
		mylists.add("3");
		mylists.add("3");
		mylists.add("3");
		mylists.add("4");
		Stream<String> listStream = mylists.stream();
		//转换Stream，流去重
		Stream<String> distinctStream = listStream.distinct();
		distinctStream.forEach(System.out::println);
		
		//综合应用
		List<Integer> nums = Lists.newArrayList(1, 1, null, 2, 3, 4, null, 5, 6, 7, 8, 9, 10);
		System.out.println("sum is:" + nums.stream().filter(num -> num != null).
		            distinct().mapToInt(num -> num * 2).
		            peek(System.out::println).skip(2).limit(4).sum());
		
		//可变汇聚
		List<Integer> lnums = Lists.newArrayList(1,1,null,2,3,4,null,5,6,7,8,9,10);
		List<Integer> numsWithoutNull = lnums.stream().filter(num -> num != null).
		            collect(() -> new ArrayList<Integer>(),
		                    (list, item) -> list.add(item),
		                    (list1, list2) -> list1.addAll(list2));
		numsWithoutNull.stream().forEach(System.out::println);
		
		List<Integer> ints = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
		System.out.println("ints sum is:" + ints.stream().reduce(0,  (sum, item) -> sum + item));
		
		//搜索相关
		List<Integer> intss = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
		System.out.println(intss.stream().allMatch(item -> item < 100));
		intss.stream().max((o1, o2) -> o1.compareTo(o2)).ifPresent(System.out::println);
	}
}